{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3e7a3822-6fa6-4c48-ac82-a233f5899bc6",
   "metadata": {},
   "source": [
    "# Codex, StrategyQA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e589bb56-ffcd-4312-ab73-145792132156",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import re\n",
    "import time\n",
    "import json\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "from tqdm import tqdm\n",
    "from pprint import pprint\n",
    "from tenacity import retry, stop_after_attempt, wait_chain, wait_fixed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "896547ab-5f31-4a3c-9cbf-82ac93cf18e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "openai.api_key = \"sk-\" # My own key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f2223bb1-58a7-44fe-80e5-70b5a3a07b91",
   "metadata": {},
   "outputs": [],
   "source": [
    "@retry(wait=wait_chain(*[wait_fixed(3) for i in range(3)] +\n",
    "                       [wait_fixed(5) for i in range(2)] +\n",
    "                       [wait_fixed(10)]))\n",
    "def completion_with_backoff(**kwargs):\n",
    "    return openai.Completion.create(**kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "808f89ec-ff5e-46da-8b97-8af5a5dbfe23",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = json.load(open('data/strategyqa_train.json'))\n",
    "train_filtered = json.load(open('data/strategyqa_train_filtered.json'))\n",
    "train_data_paragraphs = json.load(open('data/strategyqa_train_paragraphs.json'))\n",
    "test_data = json.load(open('data/strategyqa_test.json'))\n",
    "dev_idx = np.load('data/dev_idx.npy')\n",
    "dev_data = [train_data[i] for i in dev_idx]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "74466322-796f-41e7-b342-b9b1d8b00002",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'qid': '9e477711fe01970389d6',\n",
       " 'term': 'Alfred Nobel',\n",
       " 'description': 'Swedish chemist, innovator, and armaments manufacturer (1833–1896)',\n",
       " 'question': 'Did Alfred Nobel write a banned book?',\n",
       " 'answer': True,\n",
       " 'facts': ['Banned books are works which are not available for free access due to government restrictions.',\n",
       "  'Alfred Nobel is the author of Nemesis, a prose tragedy in four acts about Beatrice Cenci',\n",
       "  \"The entire stock of Nemesis was destroyed immediately after Nobel's death except for three copies, being regarded as scandalous and blasphemous. \"],\n",
       " 'decomposition': ['What literary works did Alfred Nobel write?',\n",
       "  'Have any of the works listed in #1 been banned?'],\n",
       " 'evidence': [[[['Alfred Nobel-21']], ['operation']],\n",
       "  [[['Alfred Nobel-21']], [['Alfred Nobel-21']]],\n",
       "  [[['Alfred Nobel-21']], ['operation']]]}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dev_data[10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d68d2275-5a72-48ba-aaac-b455d8025698",
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_ans(ans_model):\n",
    "    ans_model = ans_model.split('\\n')\n",
    "    ans = []\n",
    "    residual = []\n",
    "    for li, al in enumerate(ans_model):\n",
    "        ans.append(al)\n",
    "        if('answer is' in al):\n",
    "            break\n",
    "    residual = list(ans_model[li + 1:])\n",
    "    ans = '\\n'.join(ans)\n",
    "    residual = '\\n'.join(residual)\n",
    "    return ans, residual"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec763536-9091-4939-914a-648ac03683b7",
   "metadata": {},
   "source": [
    "# Complex Prompt Acc 71.88"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "13141bda-e9ca-4da7-b1d2-b4509deed0de",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_complex_step = open('lib_prompt/prompt_complex_step.txt').read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ea64856d-e93b-4016-8106-2319afd666d6",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 800/800 [2:45:41<00:00, 12.43s/it]\n"
     ]
    }
   ],
   "source": [
    "acc = 0\n",
    "total = 0\n",
    "with open('outputs/dev_codex_complex_step.txt', 'w') as fd:\n",
    "    for d in tqdm(dev_data):\n",
    "        q = d['question']\n",
    "        a = d['answer']\n",
    "        if(a is True): a = 'yes'\n",
    "        else: a = 'no'\n",
    "        \n",
    "        prompt_q = prompt_complex_step + '\\nQ: ' + q + '\\n'\n",
    "        prompt_q += 'A:'\n",
    "\n",
    "        response = completion_with_backoff(model=\"code-davinci-002\", \n",
    "                                            prompt=prompt_q, \n",
    "                                            temperature=0, \n",
    "                                            max_tokens=256)\n",
    "\n",
    "        ans_model = response['choices'][0]['text']\n",
    "        ans_model, _ = extract_ans(ans_model)\n",
    "        fd.write('Q: %s\\nA_model:\\n%s\\nA:\\n%s\\n\\n' % (q, ans_model, a))\n",
    "        \n",
    "        ans_ = ans_model.split('answer is ')\n",
    "        if(len(ans_) > 1 and 'yes' in ans_[1]): ans_ = 'yes'\n",
    "        else: ans_ = 'no'\n",
    "        \n",
    "        if(ans_ == a): acc += 1\n",
    "        total += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "00a7faa2-cce4-47cb-9a9b-9157ea60bbf8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total 800 correct 575 acc 0.7188\n"
     ]
    }
   ],
   "source": [
    "print('Total %d correct %d acc %.4f' % (total, acc, acc / total))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f486fedb-c81a-44af-8845-aafacc7fb0f1",
   "metadata": {},
   "source": [
    "# Complex Prompt with Conjunction, Acc 73.88"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9e6fb401-ba7d-4c8d-b6de-d2c8a927634e",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_complex_conjunction = open('lib_prompt/prompt_complex_conjunction.txt').read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "d101ce4c-80a9-447d-8368-03a9f31bec4c",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 800/800 [2:44:04<00:00, 12.31s/it]\n"
     ]
    }
   ],
   "source": [
    "acc = 0\n",
    "total = 0\n",
    "with open('outputs/dev_codex_complex_conjunction.txt', 'w') as fd:\n",
    "    for d in tqdm(dev_data):\n",
    "        q = d['question']\n",
    "        a = d['answer']\n",
    "        if(a is True): a = 'yes'\n",
    "        else: a = 'no'\n",
    "        \n",
    "        prompt_q = prompt_complex_conjunction + '\\nQ: ' + q + '\\n'\n",
    "        prompt_q += 'A:'\n",
    "\n",
    "        response = completion_with_backoff(model=\"code-davinci-002\", \n",
    "                                            prompt=prompt_q, \n",
    "                                            temperature=0, \n",
    "                                            max_tokens=256)\n",
    "\n",
    "        ans_model = response['choices'][0]['text']\n",
    "        ans_model, _ = extract_ans(ans_model)\n",
    "        fd.write('Q: %s\\nA_model:\\n%s\\nA:\\n%s\\n\\n' % (q, ans_model, a))\n",
    "        \n",
    "        ans_ = ans_model.split('answer is ')\n",
    "        if(len(ans_) > 1 and 'yes' in ans_[1]): ans_ = 'yes'\n",
    "        else: ans_ = 'no'\n",
    "        \n",
    "        if(ans_ == a): acc += 1\n",
    "        total += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b32fc865-09fc-4fb5-a468-aa6434f366f2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total 800 correct 591 acc 0.7388\n"
     ]
    }
   ],
   "source": [
    "print('Total %d correct %d acc %.4f' % (total, acc, acc / total))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
